//
//  CommunicationViewController.m
//  ToYourHeartNews
//
//  Created by XJing on 16/1/17.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥. All rights reserved.
//

#import "CommunicationViewController.h"
#import "AfNetWorkingHandler.h"
#import "FindsModel.h"
#import "TitlesModel.h"
#import <UIImageView+WebCache.h>
#import "FindCell.h"
#import "TitlesCell.h"
#import "LunbotuDetailViewController.h"
#import "TitleViewController.h"
#import "FindViewController.h"
#import <MJRefresh.h>
#import "BlackManager.h"
#import "SetBlack.h"
#import "TitleDataBaseManager.h"
#import "LoginViewController.h"
#import "MBProgressHUDManager.h"//加载时的小菊花
@interface CommunicationViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate, pushLogInDelegate>
@property (nonatomic, retain)UIScrollView *scroll;
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)UITableView *findTableView;
@property (nonatomic, retain)NSMutableArray *findArr;
@property (nonatomic, retain)NSMutableArray *titleArr;
@property (nonatomic, assign)NSInteger number;
@property (nonatomic, retain)UISegmentedControl *seg;
@end

@implementation CommunicationViewController
-(void)dealloc
{
    [_scroll release];
    [_tableView release];
    [_findTableView release];
    [_findArr release];
    [_titleArr release];
    [_seg release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.seg = [[UISegmentedControl alloc]initWithItems:@[@"话题", @"发现"]];
    _seg.frame = CGRectMake(100, 5, 100, 30) ;
    _seg.selectedSegmentIndex = 0;
    //分段内部颜色
//    seg.tintColor = [UIColor whiteColor];
    //添加点击事件
    [_seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = _seg;
    [_seg release];
    //话题页数据处理
    [self dataHandler];
    //发现页数据
    [self dataHandler2];
    //scroll
    self.scroll = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    _scroll.contentSize = CGSizeMake(2 * self.view.frame.size.width, self.view.frame.size.height);
//    _scroll.backgroundColor = [UIColor yellowColor];
    _scroll.bounces = NO;
    _scroll.pagingEnabled = YES;
    _scroll.delegate = self;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:_scroll];
    [_scroll release];
    
    //隐藏上下边栏
    //是否实现了方法
    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
        self.automaticallyAdjustsScrollViewInsets = NO;//取消scrollview的内容自动调整
        UIEdgeInsets insets = self.tableView.contentInset ;//tableView边界预留
        insets.top = self.navigationController.navigationBar.bounds.size.height;//让上边界的预留值和导航栏相等
        //        self.tableView.contentInset = insets;
        self.tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
        //把修改后的边界预留值赋值给tableView
        self.tableView.scrollIndicatorInsets = insets;//滚动指标点到滚动视图的边缘的距离
        self.findTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
        //把修改后的边界预留值赋值给tableView
        self.findTableView.scrollIndicatorInsets = insets;//滚动指标点到滚动视图的边缘的距离
    }

    
    //话题页面
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    [_tableView registerClass:[TitlesCell class] forCellReuseIdentifier:@"cellh"];
    [_scroll addSubview:_tableView];
    [_tableView release];
    
    //发现页面
    self.findTableView = [[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _findTableView.dataSource = self;
    _findTableView.delegate = self;
    _findTableView.contentInset = UIEdgeInsetsMake(64, 0, 120, 0);
    [_findTableView registerClass:[FindCell class] forCellReuseIdentifier:@"cellf"];
    [_scroll addSubview:_findTableView];
    [_findTableView release];
    
    //话题页下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(dataHandler)];
    [_tableView.mj_header beginRefreshing];
    
    //话题页上拉加载
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadnewdata)];
    if (_titleArr.count != 0) {
        [_tableView.mj_footer beginRefreshing];
    }
    self.number = 10;
    
    //发现页下拉刷新
    self.findTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(dataHandler2)];
    [_findTableView.mj_header beginRefreshing];
    
    //发现页上拉加载
    self.findTableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadnewdata2)];
    if (_findArr.count != 0) {
        [_findTableView.mj_footer beginRefreshing];
    }
//    self.number = 10;
    
    
    
}
//滑动时隐藏上下边栏
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    if (velocity.y > 0) {
        self.navigationController.navigationBar.hidden = YES;
        self.tabBarController.tabBar.hidden = YES;
    }else{
        self.navigationController.navigationBar.hidden = NO;
        self.tabBarController.tabBar.hidden = NO;
    }
}
//判断结束拖拽之后的偏移量 改变segment的selectedIndex
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x < self.view.frame.size.width / 2 && scrollView.contentOffset.x > 0) {
        _seg.selectedSegmentIndex = 0;
    }
    if(scrollView.contentOffset.x > self.view.frame.size.width / 2)
    {
        _seg.selectedSegmentIndex = 1;
    }
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}
//点击cell进入详情
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_tableView]) {
        TitleViewController *titleVC = [[TitleViewController alloc]init];
        self.hidesBottomBarWhenPushed = YES;
        TitlesModel *m = _titleArr[indexPath.row];
        titleVC.model = m;
        [self.navigationController pushViewController:titleVC animated:YES];
        self.hidesBottomBarWhenPushed = NO;
        [titleVC release];
    }
    if ([tableView isEqual:_findTableView]) {
        FindViewController *findVC = [[FindViewController alloc]init];
        self.hidesBottomBarWhenPushed = YES;
        FindsModel *m = _findArr[indexPath.row];
        findVC.titleName = m.title;
        findVC.path = m.api_url;
        [self.navigationController pushViewController:findVC animated:YES];
        self.hidesBottomBarWhenPushed = NO;
        [findVC release];
    }
    
}
//话题页上拉加载
- (void)loadnewdata
{
    NSString *str = [NSString stringWithFormat:@"http://c.m.163.com/newstopic/list/expert/%ld-10.html", (long)self.number] ;
    [AfNetWorkingHandler GetWithStr:str complection:^(id result) {
        NSDictionary *dic = result[@"data"];
        NSArray *arr = dic[@"expertList"];
        NSArray *arrTemp = [NSArray array];
        arrTemp = [TitlesModel modelHanderWithArray:arr];
        for (NSInteger i = 0; i < 10; i++) {
            [self.titleArr addObject:arrTemp[i]];
        }
        [_tableView reloadData];
    }];
    [_tableView.mj_footer endRefreshing];
    self.number += 10;
}
//发现页上拉加载
-(void)loadnewdata2
{
    NSString *str = @"http://dis.myzaker.com/api/list_discussion.php?_appid=iphone&_bsize=640_1136&_dev=iPhone%2C8.4.1&_idfa=B04A9F17-39FD-4ADF-9D92-9F93CE548EFE&_lat=38.882515&_lbs_city=%E5%A4%A7%E8%BF%9E&_lbs_province=%E8%BE%BD%E5%AE%81&_lng=121.539757&_mac=02%3A00%3A00%3A00%3A00%3A00&_net=wifi&_udid=ECFC153B-2246-4EB0-8D9F-510516697A0C&_uid=&_utoken=&_v=6.4.6&_version=6.45&act=more_discussion&except_recommend=Y";
    [AfNetWorkingHandler GetWithStr:str complection:^(id result) {
        NSArray *arr = result[@"data"][@"list"];
        NSArray *arrTemp = [NSArray array];
        arrTemp = [FindsModel modelHanderWithArray:arr];
        for (NSInteger i = 0; i < arrTemp.count; i++) {
            [self.findArr addObject:arrTemp[i]];
        }

        [_findTableView reloadData];
    }];
    [_findTableView.mj_header endRefreshing];
}

//话题页的数据处理
-(void)dataHandler
{
    //添加加载小菊花
    [MBProgressHUDManager showHUDtoView:self.view string:@"努力加载中"];
    NSString *str = @"http://c.m.163.com/newstopic/list/expert/0-10.html";
    [AfNetWorkingHandler GetWithStr:str complection:^(id result) {
        //  专家数组
        NSLog(@"%@", result);
        NSDictionary *dic = result[@"data"];
        NSArray *arr = dic[@"expertList"];
        self.titleArr = [NSMutableArray array];
        self.titleArr = [TitlesModel modelHanderWithArray:arr];
        NSLog(@"专家:%@", _titleArr);
        [_tableView reloadData];
        [MBProgressHUDManager removeHUD];
    }];
    [_tableView.mj_header endRefreshing];
}
//发现页的数据处理
-(void)dataHandler2
{
    //添加加载小菊花
    [MBProgressHUDManager showHUDtoView:self.view string:@"努力加载中"];
    NSString *str = @"http://dis.myzaker.com/api/list_discussion.php?_appid=iphone&_bsize=640_1136&_dev=iPhone%2C8.4.1&_idfa=B04A9F17-39FD-4ADF-9D92-9F93CE548EFE&_lat=38.882465&_lng=121.539864&_mac=02%3A00%3A00%3A00%3A00%3A00&_net=wifi&_udid=ECFC153B-2246-4EB0-8D9F-510516697A0C&_uid=&_utoken=&_v=6.4.5&_version=6.44&except_subscribe=N";
    self.findArr = [NSMutableArray array];
    [AfNetWorkingHandler GetWithStr:str complection:^(id result) {
        NSArray *arr = result[@"data"][@"list"];
        self.findArr =  [FindsModel modelHanderWithArray:arr];
//        NSLog(@"find:%@", _findArr);
        [_findTableView reloadData];
        [MBProgressHUDManager removeHUD];
    }];
    [_findTableView.mj_header endRefreshing];
}
//根据不同的tableView设置不同高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_findTableView]) {
        return 90;
    }else if([tableView isEqual:_tableView])
    {
        return 320;
    }else{
        return 0;
    }
}
//判断是哪个tableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual: _tableView]) {
        return _titleArr.count;
    }else{
        return _findArr.count;
    }
}
//设置夜间模式
-(void)setLightDayModel
{
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    self.tabBarController.tabBar.barStyle = UIBarStyleDefault;
    [SetBlack setBackgroundColorWithView:self.tableView];
    [SetBlack setBackgroundColorWithView:self.findTableView];
}
-(void)setNightDayModel
{
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.tabBarController.tabBar.barStyle = UIBarStyleBlack;
    [SetBlack setBackgroundColorWithView:self.tableView];
    [SetBlack setBackgroundColorWithView:self.findTableView];
}
//进入页面之前更新页面
-(void)viewWillAppear:(BOOL)animated
{
    [_tableView reloadData];
    [_findTableView reloadData];
}
#pragma mark - 创建tableView中cell样式
//创建tableView中cell样式
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_tableView]) {
        TitlesCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellh" forIndexPath:indexPath];
        cell.delegate = self;
        if (self.titleArr.count != 0) {
            //根据夜间模式设置背景和字体颜色
            [SetBlack setCellColorWithCell:cell];
            [SetBlack setLableTitleColorWithArr:@[cell.jieshaoLable, cell.contentsLable]];
            TitlesModel *m = _titleArr[indexPath.row];
            [cell.img sd_setImageWithURL:[NSURL URLWithString:m.picurl]placeholderImage:[UIImage imageNamed:@"pocket.png"]];
            [cell.photo sd_setImageWithURL:[NSURL URLWithString:m.headpicurl]placeholderImage:[UIImage imageNamed:@"pocket.png"]];
            cell.model = m;
            cell.nameLable.text = m.name;
            cell.jieshaoLable.text = m.alias;
            cell.contentsLable.text = [[m.concernCount.stringValue stringByAppendingString:@"关注"] stringByAppendingString:@" |"] ;
            cell.contentsLable.font = [UIFont systemFontOfSize:14];
            cell.kindLable.text = m.classification;
            //创建cell时 先执行cell中的init 然后执行tableview中cellForRowAtIndexPath方法 给cell中内容复制 再执行cell中的layout方法
            
        }
        
        return cell;
    }
    if ([tableView isEqual:_findTableView]) {
        FindCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellf" forIndexPath:indexPath];
        //只有数组中有值的时候才执行赋值
        if (_findArr.count != 0) {
            [SetBlack setCellColorWithCell:cell];
            [SetBlack setLableTitleColorWithArr:@[cell.titlelable]];
            FindsModel *m = _findArr[indexPath.row];
            [cell.img sd_setImageWithURL:[NSURL URLWithString:m.pic]];
            cell.titlelable.text = m.title;
            cell.stitleLable.text = m.stitle;
        }
        return cell;
    }else{
        return 0;
    }
    
}
-(void)pushLogin{
    self.hidesBottomBarWhenPushed = YES;
    LoginViewController *login = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:login animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    [login release];
}
//segment触发的方法
-(void)segAction:(UISegmentedControl *)seg
{
    if (seg.selectedSegmentIndex == 0) {
        _scroll.contentOffset = CGPointMake(0, 0);
    }
    if (seg.selectedSegmentIndex == 1) {
        _scroll.contentOffset = CGPointMake(self.view.frame.size.width, 0);
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
